from PyQt4 import QtGui,QtCore 
import qt_ui.ui_sql
import utils.database
import utils.dialogs

class FrmSQL(QtGui.QDialog,qt_ui.ui_sql.Ui_sql):
    
    def __init__(self,parent):
        QtGui.QDialog.__init__(self,parent)
        self.setupUi(self)
        QtCore.QObject.connect(self.pushButton_3,QtCore.SIGNAL("clicked()"),self.execSql)
        QtCore.QObject.connect(self.pushButton_2,QtCore.SIGNAL("clicked()"),self.export)
        QtCore.QObject.connect(self.pushButton_4,QtCore.SIGNAL("clicked()"),self.showSQLresult)
        self.textEdit.setText("select * from profile")
        self.showSQLresult()
        self.show()
        
    def execSql(self):
        sql = self.textEdit.textCursor().selectedText()
        if (sql == ""):
            sql = self.textEdit.toPlainText()
        
        sqls = sql.split(";")
        
        for cmd in sqls:
            if (cmd != ""):
                fields = utils.database.execSql(cmd)
        
        if type(fields) != "NoneType":
            self.tableWidget.setRowCount(len(fields))
            self.tableWidget.setColumnCount(len(fields[0]))
            self.tableWidget.setHorizontalHeaderLabels(fields[0].keys())

            for i, row in enumerate(fields):
                for (j, (column, value)) in enumerate(row.items()):
                    item = QtGui.QTableWidgetItem(str(value))
                    self.tableWidget.setItem(i,j,item)
            
            self.showSQLresult()
                
    
    def export(self):
        saveDialog = QtGui.QFileDialog(self,"Export results to ")
        saveDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        saveDialog.setViewMode(QtGui.QFileDialog.List)
        
        arquivo = QtCore.QStringList()
        
        csv = QtCore.QFile('/home/upmauro/aff.csv')
        csv.open(QtCore.QFile.ReadWrite)
        for x in range(self.tableWidget.rowCount()):
            linha = "\n"
            for y in range(self.tableWidget.columnCount()):
                linha = linha + self.tableWidget.item(x,y).text() + ";"
            csv.writeData(linha)
        csv.close()

    
    def showSQLresult(self):
        rect = self.geometry()
        if self.groupResult.isHidden():
            self.groupResult.show()
            rect.setHeight(580)
            self.setGeometry(rect)
            self.label.setText("<b>%s</b> fields" % self.tableWidget.rowCount())
        else:
            rect.setHeight(240)
            self.groupResult.hide()
            self.setGeometry(rect)
            utils.dialogs.center(self)
        utils.dialogs.center(self)
        self.updateGeometry()